package com.buba.service.impl;

import com.buba.mapper.DailyRecordMapper;
import com.buba.service.DailyRecordService;
import com.buba.utils.WebSocketServer;
import entity.*;
import org.checkerframework.checker.units.qual.K;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import result.CommonResult;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * LC: 2022-11-16 10:16
 */
@Service
public class DailyRecordServiceImpl implements DailyRecordService {


    @Autowired
    DailyRecordMapper diaryMapper;

    @Autowired
    WebSocketServer webSocketServer;

    @Autowired
    RedisTemplate<Object,Object>  rt;

    static String VIDEO_ALL_TALK_INFO_BEFORE ="videoAllTalk:";

    static String VIDEOTALK_INFO_BEFORE ="videoTalk:";
    static String categoryTreeKeyLocks = "lock2:" + VIDEOTALK_INFO_BEFORE;

    static String ReplyComment = "ReplyComment";
    static String ReplyCommentLocks = "lock3:" + ReplyComment;

    static String Like ="like:";
    /**
     * 根据id查询日记
     * @param id
     * @return
     */
    @Override
    public List<DailyRecordEntity> getDailyRecordById(Integer id,Integer userId) {
        // 根据id查询日记
        List<DailyRecordEntity> dailyRecordEntityList =diaryMapper.getDailyRecordById(id,userId);
        // 查找日记图片
        for (int i = 0;i < dailyRecordEntityList.size();i++) {
            String[] split = dailyRecordEntityList.get(i).getDiaryRecordFileId().split(",");
            List<String> sss = new ArrayList<>();
            for (String s : split) {
                String ss = diaryMapper.selectUrl(s);
                sss.add(ss);
        }
            // 把图片存进集合里
            dailyRecordEntityList.get(i).setUrl(sss);
//            dailyRecordEntityList.get(i).setUrl(diaryMapper.selectUrl(dailyRecordEntityList.get(i).getDiaryRecordFileId()));
        }
        return dailyRecordEntityList;
    }

    /**
     * 新增浏览量
     * @param dailyRecordEntity
     * @return
     */
    @Override
    public Integer editDailyRecordBrowse(DailyRecordEntity dailyRecordEntity) {
        dailyRecordEntity.setDiaryRecordBrowse(dailyRecordEntity.getDiaryRecordBrowse()+1);
        return diaryMapper.editDailyRecordBrowse(dailyRecordEntity);
    }

    /**
     * 新增评论
     * @param commentEntiry
     * @return
     */
    @Override
    public CommonResult saveComment(CommentEntiry commentEntiry) {
        try{
            //1.更新数据库之前，删除缓存里的旧数据
            rt.opsForValue().getOperations().delete(VIDEO_ALL_TALK_INFO_BEFORE+commentEntiry.getCommentDiaryRecordId()+commentEntiry.getCommentDictionaries());
        }catch (Exception ex){
            ex.printStackTrace();
        }
        try {
            int insert = 0;
            commentEntiry.setCreateTime(new Date());
            commentEntiry.setCommentTime(new Date());
            commentEntiry.setDelFlag(0);
            commentEntiry.setCommentUserId(2);
            DailyRecordEntity dailyRecordEntity = new DailyRecordEntity();
            // 根据id查询日记
            DailyRecordEntity list = diaryMapper.getCommentByIds(commentEntiry.getCommentDiaryRecordId());
            // 增加评论数量
            dailyRecordEntity.setDiaryRecordNumber(list.getDiaryRecordNumber()+1);
            dailyRecordEntity.setDailyRecordId(commentEntiry.getCommentDiaryRecordId());
             insert = diaryMapper.updateDiaryRecordNumber(dailyRecordEntity);
             // 新增评论
             insert = diaryMapper.saveComment(commentEntiry);
            if (insert>0){
                return CommonResult.ok();
            }
        }catch (Exception ex){
            throw new RuntimeException("更新数据库失败");
        }
        try{
            //2.更新成功后，再次删除缓存里的旧数据
            rt.opsForValue().getOperations().delete(VIDEO_ALL_TALK_INFO_BEFORE+commentEntiry.getCommentDiaryRecordId()+commentEntiry.getCommentDictionaries());
        }catch (Exception ex){
            ex.printStackTrace();
        }
//        String AllTalkKey = VIDEO_ALL_TALK_INFO_BEFORE+commentEntiry.getCommentDiaryRecordId()+commentEntiry.getCommentDictionaries();
//        commentEntiry.setCreateTime(new Date());
//        commentEntiry.setCommentTime(new Date());
//        commentEntiry.setDelFlag(0);
//        commentEntiry.setCommentUserId(1);
//        String key = VIDEOTALK_INFO_BEFORE+commentEntiry.getCommentDiaryRecordId()+commentEntiry.getCommentDictionaries();;
//        int insert = diaryMapper.saveComment(commentEntiry);
//        if (insert>0){
//            rt.delete(key);
//            rt.opsForValue().set(AllTalkKey,commentEntiry);
//            return CommonResult.ok();
//        }
        return CommonResult.fail();
    }

    /**
     * 根据id查询评论
     * @param id
     * @return
     */
    @Override
    public  List<CommentEntiry> getCommentById(Integer id, String commentDictionaries,Integer userId) {
        String key= VIDEO_ALL_TALK_INFO_BEFORE + id + commentDictionaries;
        long start = System.currentTimeMillis();
        //1.从缓存中查询数据
        Object list = (Object) rt.opsForValue().get(key);
        //2.缓存没查到
        if(list == null){
            //2.枪锁
            RedissonClient redissonClient = Redisson.create();
            RLock lock = redissonClient.getLock(categoryTreeKeyLocks);
            lock.lock(10, TimeUnit.SECONDS);
            try{
                //3.再次从缓存中查询数据
                list =  rt.opsForValue().get(key);
                //4.缓存中没有查到数据
                if(list == null){
//                    4.1从数据库查询数据
                    List<CommentEntiry>  lists =  diaryMapper.getCommentById(id,commentDictionaries,userId);
                    for (int i=lists.size()-1;i>=0;i--){
                        if (lists.get(i).getDelFlag()==1){
                            lists.remove(i);
                        }
                    }
                    // 递归
                    List<CommentEntiry> newevaluateEntity = new ArrayList<>();
                    for(CommentEntiry evaluateEntity:lists){
                        if(evaluateEntity.getCommentPid() == 0){
                            newevaluateEntity.add(getChild(evaluateEntity,lists));
                        }
                    }
                    if(newevaluateEntity != null){
                        //4.2从数据库查到数据后，放到缓存中
                        rt.opsForValue().set(key,newevaluateEntity);
                        return newevaluateEntity;

                    }
                }
            }finally {
                //5.解锁
                lock.unlock();
                redissonClient.shutdown();
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("花费时间：" + (end - start));
        System.out.println(list);
        return (List<CommentEntiry>) list;
    }

    /**
     * 递归方法
     * @param evaluateEntity
     * @param evaluateEntityList
     * @return
     */
    private CommentEntiry getChild(CommentEntiry evaluateEntity, List<CommentEntiry> evaluateEntityList) {
        List<CommentEntiry> newevaluateEntity = new ArrayList<>();
        // 子集查找父级
        for(CommentEntiry childEvaluate:evaluateEntityList){
            if(evaluateEntity.getCommentId().equals(childEvaluate.getCommentPid())){
                newevaluateEntity.add(getChild(childEvaluate,evaluateEntityList));
            }
        }
        // 存进集合
        evaluateEntity.setChilds(newevaluateEntity);
        return evaluateEntity;
    }

    /**
     * 根据id查询评论数量
     * @param id
     * @return
     */
    @Override
    public String getCommentNum(Integer id, String commentDictionaries) {
        String ss = diaryMapper.getCommentNum(id,commentDictionaries);
        return ss;
    }

    /**
     * 点赞
     * @param
     * @return
     */
    @Override
    public CommonResult getKudosNum(KudosEntity kudosEntity) {
        try {
            int insert = 0;
            insert = diaryMapper.getKudosNum(kudosEntity);
            // 查找点赞日记
            DailyRecordEntity dailyRecordEntity = new DailyRecordEntity();
            DailyRecordEntity list = diaryMapper.getCommentByIds(kudosEntity.getKudosWholeId());
            // 新增点赞数量
            dailyRecordEntity.setDiaryRecordNumber(list.getDiaryRecordWhether()+1);
            dailyRecordEntity.setDailyRecordId(kudosEntity.getKudosWholeId());
            insert = diaryMapper.updateKudosNum(dailyRecordEntity);
            if (insert>0){
                return CommonResult.ok();
            }
        }catch (Exception ex){
            throw new RuntimeException("更新数据库失败");
        }
        return CommonResult.ok("404");
    }

    /**
     * 根据id查询日记本图片
     * @param id
     * @return
     */
    @Override
    public List<DiaryEntity> getdiaryFile(Integer id) {
        List<DiaryEntity>  diaryEntityList = diaryMapper.getDailyById(id);
        //查找图片
        for (int i = 0;i < diaryEntityList.size();i++) {
            String[] split = diaryEntityList.get(i).getDiaryFileId().split(",");
            List<String> sss = new ArrayList<>();
            for (String s : split) {
                String ss = diaryMapper.selectUrl(s);
                sss.add(ss);
            }
            // 把图片存进集合
            diaryEntityList.get(i).setUrl(sss);
        }
        return diaryEntityList;
    }

    /**
     * 根据id查询日记本用户
     * @param id
     * @return
     */
    @Override
    public  List<DiaryEntity> getdiaryUser(Integer id) {
        return  diaryMapper.getdiaryUser(id);
    }

    /**
     * 查询是否点赞
     * @param
     * @return
     */
    @Override
    public CommonResult getKudosById(Integer id, Integer kudosDictionaries,Integer kudosUserId) {
        List<KudosEntity> list = diaryMapper.getKudosById(id,kudosDictionaries,kudosUserId);
        if(list.size()>0&&list!=null){
            DailyRecordEntity dailyRecordEntity = new DailyRecordEntity();
            KudosEntity kudosEntity = new KudosEntity();
            // 以点赞 取消
            for(KudosEntity ss:list){
                kudosEntity.setKudosId(ss.getKudosId());
                kudosEntity.setKudosWhether(1);
                //点赞取消
                int insert = diaryMapper.updateKudos(kudosEntity);
                if(insert>0){
                    // 点赞数量-1
                    DailyRecordEntity list1 = diaryMapper.getCommentByIds(ss.getKudosWholeId());
                    dailyRecordEntity.setDiaryRecordWhether(list1.getDiaryRecordWhether()-1);
                    dailyRecordEntity.setDailyRecordId(ss.getKudosWholeId());
                    insert = diaryMapper.updateKudosNum(dailyRecordEntity);
                    if(insert>0){
                        return CommonResult.ok("200");
                    }
                }
            }
        }else{
            // 没点赞 修改点赞（查找用户是否点赞过）
            List<KudosEntity> KudosEntitylist = diaryMapper.getKudosByIds(id,kudosDictionaries,kudosUserId);
            if(KudosEntitylist.size()>0&&KudosEntitylist!=null){
                DailyRecordEntity dailyRecordEntity = new DailyRecordEntity();
                KudosEntity kudosEntity = new KudosEntity();
                for(KudosEntity ss:KudosEntitylist){
                    // 点赞
                    kudosEntity.setKudosId(ss.getKudosId());
                    kudosEntity.setKudosWhether(0);
                    int insert = diaryMapper.updateKudos(kudosEntity);
                    if(insert>0){
                        // 点赞数量加1
                        DailyRecordEntity list1 = diaryMapper.getCommentByIds(ss.getKudosWholeId());
                        dailyRecordEntity.setDiaryRecordWhether(list1.getDiaryRecordWhether()+1);
                        dailyRecordEntity.setDailyRecordId(ss.getKudosWholeId());
                        insert = diaryMapper.updateKudosNum(dailyRecordEntity);
                        if (insert>0){
                            return CommonResult.ok("201");
                        }
                    }
                }
            } else {
                // 没点赞过 新增点赞
                int insert = 0;
                KudosEntity kudosEntity = new KudosEntity();
                kudosEntity.setKudosUserId(kudosUserId);
                kudosEntity.setKudosWholeId(id);
                kudosEntity.setKudosDictionaries(kudosDictionaries);
                insert = diaryMapper.getKudosNum(kudosEntity);
                if(insert>0){
                    // 点赞数量+1
                    DailyRecordEntity dailyRecordEntity = new DailyRecordEntity();
                    DailyRecordEntity list1 = diaryMapper.getCommentByIds(kudosEntity.getKudosWholeId());
                    dailyRecordEntity.setDiaryRecordWhether(list1.getDiaryRecordWhether()+1);
                    dailyRecordEntity.setDailyRecordId(kudosEntity.getKudosWholeId());
                    insert = diaryMapper.updateKudosNum(dailyRecordEntity);
                    if(insert>0){
                        return CommonResult.ok("202");
                    }
                }
            }
        }
        return CommonResult.ok("404");
    }

    /**
     * 日记本详情轮播图片
     * @param id
     * @return
     */
    @Override
    public List<DailyRecordEntity> getDailyRecordFileById(Integer id) {
        List<DailyRecordEntity> dailyRecordEntityList =diaryMapper.getDailyRecordFileById(id);
        // 查找图片
        for (int i = 0;i < dailyRecordEntityList.size();i++) {
            String[] split = dailyRecordEntityList.get(i).getDiaryRecordFileId().split(",");
            List<String> sss = new ArrayList<>();
            for (String s : split) {
                String ss = diaryMapper.selectUrl(s);
                sss.add(ss);
            }
            // 把图片存进集合
            dailyRecordEntityList.get(i).setUrl(sss);
        }
        return dailyRecordEntityList;
    }

    /**
     * 评论点赞
     * @param id
     * @param kudosDictionaries
     * @param kudosUserId
     * @param commentDiaryRecordId
     * @return
     */
    @Override
    public CommonResult getCommentKudosById(Integer id, Integer kudosDictionaries,Integer kudosUserId,Integer commentDiaryRecordId) {
        try{
            //1.更新数据库之前，删除缓存里的旧数据
            rt.opsForValue().getOperations().delete(VIDEO_ALL_TALK_INFO_BEFORE+commentDiaryRecordId+""+1);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        List<KudosEntity> list = diaryMapper.getKudosById(id,kudosDictionaries,kudosUserId);
        if(list.size()>0&&list!=null){
            KudosEntity kudosEntity = new KudosEntity();
            CommentEntiry commentEntiry = new CommentEntiry();
            // 以点赞 取消
            for(KudosEntity ss:list){
                // 取消点赞
                kudosEntity.setKudosId(ss.getKudosId());
                kudosEntity.setKudosWhether(1);
                int insert = diaryMapper.updateKudos(kudosEntity);
                if(insert>0){
                    // 点赞数量减1
                    CommentEntiry list1 = diaryMapper.getCommentByIdNum(ss.getKudosWholeId());
                    commentEntiry.setKudosNum(list1.getKudosNum()-1);
                    commentEntiry.setCommentId(Long.valueOf(ss.getKudosWholeId()));
                    insert = diaryMapper.updateCommentNum(commentEntiry);
                    if(insert>0){
                        return CommonResult.ok("200");
                    }
                }
            }
        }else{
            // 没点赞 修改点赞（查找用户是否点赞过）
            List<KudosEntity> KudosEntitylist = diaryMapper.getKudosByIds(id,kudosDictionaries,kudosUserId);
            if(KudosEntitylist.size()>0&&KudosEntitylist!=null){
                KudosEntity kudosEntity = new KudosEntity();
                CommentEntiry commentEntiry = new CommentEntiry();
                for(KudosEntity ss:KudosEntitylist){
                    // 点赞
                    kudosEntity.setKudosId(ss.getKudosId());
                    kudosEntity.setKudosWhether(0);
                    int insert = diaryMapper.updateKudos(kudosEntity);
                    if(insert>0){
                        // 点赞数量+1
                        CommentEntiry list1 = diaryMapper.getCommentByIdNum(ss.getKudosWholeId());
                        commentEntiry.setKudosNum(list1.getKudosNum()+1);
                        commentEntiry.setCommentId(Long.valueOf(ss.getKudosWholeId()));
                        insert = diaryMapper.updateCommentNum(commentEntiry);
                        if(insert>0){
                            return CommonResult.ok("201");
                        }
                    }
                }
            }else {
                // 没点赞过 新增点赞
                int insert = 0;
                KudosEntity kudosEntity = new KudosEntity();
                kudosEntity.setKudosUserId(kudosUserId);
                kudosEntity.setKudosWholeId(id);
                kudosEntity.setKudosDictionaries(kudosDictionaries);
                insert = diaryMapper.getKudosNum(kudosEntity);
                if(insert>0){
                    // 增加点赞数量
                    CommentEntiry commentEntiry = new CommentEntiry();
                    CommentEntiry list1 = diaryMapper.getCommentByIdNum(kudosEntity.getKudosWholeId());
                    commentEntiry.setKudosNum(list1.getKudosNum()+1);
                    commentEntiry.setCommentId(Long.valueOf(kudosEntity.getKudosWholeId()));
                    insert = diaryMapper.updateCommentNum(commentEntiry);
                    if(insert>0){
                        return CommonResult.ok("202");
                    }
                }
            }
        }
        return CommonResult.ok("404");
    }

    /**
     * 根据id查询日记评论、点赞
     * @param id
     * @return
     */
    @Override
    public DailyRecordEntity getDailyRecordIdOne(Integer id) {
        return diaryMapper.getDailyRecordIdOne(id);
    }

    /**
     * 新增关注
     * @param id
     * @return
     */
    @Override
    public List<FollowUserEntiry> getFollowUserId(Integer id,Integer userId) {
        // 查找是否关注
        List<FollowUserEntiry> dailyRecordEntityList =diaryMapper.getFollowUserEntiry(userId,id);
        List<FollowUserEntiry> dailyRecordEntityList1 =diaryMapper.getFollowUserEntiry1(userId,id);
        if(dailyRecordEntityList.size()>0){
            // 取消关注
            diaryMapper.delectFollowUserEntiry(userId,id);
            return dailyRecordEntityList;
        }else if(dailyRecordEntityList1.size()>0){
//            webSocketServer.sendMessage("已关注");
           // 关注（添加取关的关注）
            diaryMapper.delectFollowUserEntiry1(userId,id);
            return dailyRecordEntityList1;
        } else {
            // 新增关注
            FollowUserEntiry followUserEntiry = new FollowUserEntiry();
            followUserEntiry.setFollowUserUserId(userId);
            followUserEntiry.setFollowUserCoverUserId(id);
            followUserEntiry.setCreateTime(new Date());
            diaryMapper.saveFollowUserId(followUserEntiry);
            return dailyRecordEntityList;
        }
    }

    /**
     * 查询关注
     * @param id
     * @return
     */
    @Override
    public List<FollowUserEntiry> getFollowUser(Integer id, Integer userId) {
        return diaryMapper.getFollowUserEntiry3(userId,id);
    }

    /**
     * 收藏
     * @param id
     * @param collectionDictionaries
     * @param collectionUserId
     * @return
     */
    @Override
    public CommonResult getCollection(Integer id, Integer collectionDictionaries, Integer collectionUserId) {
        return null;
//        List<CollectionEntiry> list = diaryMapper.getCollection(id,collectionDictionaries,collectionUserId);
//        if(list.size()>0){
//            // 以点赞 取消
//            for(CollectionEntiry ss:list){
//                CollectionEntiry collectionEntiry = new CollectionEntiry();
//                collectionEntiry.setCollectionId(ss.getCollectionId());
//                collectionEntiry.setDelFlag(1);
//                int insert = diaryMapper.updateCollection(collectionEntiry);
//                DailyRecordEntity dailyRecordEntity = new DailyRecordEntity();
//                DailyRecordEntity list1 = diaryMapper.getCollectionByIds(ss.getCollectionWholeId());
//                dailyRecordEntity.setDiaryRecordCollection(list1.getDiaryRecordCollection()-1);
//                dailyRecordEntity.setDailyRecordId(ss.getCollectionWholeId());
//                insert = diaryMapper.updateCollectionNum(dailyRecordEntity);
//                return CommonResult.ok("200");
//            }
//        }else{
//            // 没点赞 修改点赞
//            List<KudosEntity> KudosEntitylist = diaryMapper.getKudosByIds(id,kudosDictionaries,kudosUserId);
//            if(KudosEntitylist.size()>0){
//                for(KudosEntity ss:KudosEntitylist){
//                    KudosEntity kudosEntity = new KudosEntity();
//                    kudosEntity.setKudosId(ss.getKudosId());
//                    kudosEntity.setKudosWhether(0);
//                    int insert = diaryMapper.updateKudos(kudosEntity);
//                    DailyRecordEntity dailyRecordEntity = new DailyRecordEntity();
//                    DailyRecordEntity list1 = diaryMapper.getCommentByIds(ss.getKudosWholeId());
//                    dailyRecordEntity.setDiaryRecordCollection(list1.getDiaryRecordCollection()+1);
//                    dailyRecordEntity.setDailyRecordId(ss.getKudosWholeId());
//                    insert = diaryMapper.updateKudosNum(dailyRecordEntity);
//                    return CommonResult.ok("201");
//                }
//            } else {
//                // 新增点赞
//                int insert = 0;
//                KudosEntity kudosEntity = new KudosEntity();
//                kudosEntity.setKudosUserId(kudosUserId);
//                kudosEntity.setKudosWholeId(id);
//                kudosEntity.setKudosDictionaries(kudosDictionaries);
//                insert = diaryMapper.getKudosNum(kudosEntity);
//                DailyRecordEntity dailyRecordEntity = new DailyRecordEntity();
//                DailyRecordEntity list1 = diaryMapper.getCommentByIds(kudosEntity.getKudosWholeId());
//                dailyRecordEntity.setDiaryRecordWhether(list1.getDiaryRecordWhether()+1);
//                dailyRecordEntity.setDailyRecordId(kudosEntity.getKudosWholeId());
//                insert = diaryMapper.updateKudosNum(dailyRecordEntity);
//                return CommonResult.ok("202");
//            }
//        }
//        return CommonResult.ok("404");
    }

    /**
     * 全查日记
     * @return
     */
    @Override
    public List<DiaryEntity> getDailyRecordRj() {
        return diaryMapper.getDailyRecordRj();
    }


}
